<!-- app/templates/create_meeting.html -->
{% extends "base.html" %}
{% block content %}
<div class="card card-pretty">
    <div class="card-body">
        <h3 class="card-title">新建组会记录</h3>
        <form method="post" action="{% if editing %}/meetings/{{ meeting.id }}/edit{% else %}/meetings{% endif %}" enctype="multipart/form-data">  <!-- 关键：指定目标接口 -->
            <div class="mb-3">
                <input class="form-control" type="text" name="title" placeholder="会议主题" required value="{{ meeting.title if meeting else '' }}">
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">会议日期</label>
                    <input class="form-control" type="date" name="meeting_time" oninput="generateJSON()" value="{{ meeting.meeting_time if meeting else '' }}">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">会议地点</label>
                    <input class="form-control" type="text" name="location" oninput="generateJSON()" value="{{ meeting.location if meeting else '' }}">
                </div>
            </div>

            <div class="mb-3">
                <label class="form-label">参会人员（逗号分隔）</label>
                <textarea class="form-control" name="participants" oninput="generateJSON()" placeholder="张三,李四,王五">{{ meeting.participants if meeting else '' }}</textarea>
            </div>


            <div class="mb-3">
                <label class="form-label">会议纪要</label>
                <textarea class="form-control" name="minutes" rows="6" oninput="generateJSON()">{{ meeting.minutes if meeting else '' }}</textarea>
            </div>

            <div class="mb-3">
                <label class="form-label">待办事项（每行一项）</label>
                <textarea class="form-control" name="todos" rows="4" oninput="generateJSON()" placeholder="任务1\n任务2">{{ meeting.todos if meeting else '' }}</textarea>
            </div>

            <!-- 隐藏字段：存储结构化内容 -->
            <textarea id="content" name="content" style="display:none;">{{ content | tojson(indent=2) if content else '' }}</textarea>

            <script>
                function generateJSON() {
                    const fields = ['meeting_time', 'location', 'participants', 'minutes', 'todos'];
                    const data = {};
                    fields.forEach(field => {
                        const el = document.querySelector(`[name="${field}"]`);
                        if (el) data[field] = el.value;
                    });
                    // 也把 title 放进去以完整体现
                    const titleEl = document.querySelector('[name="title"]');
                    if (titleEl) data['title'] = titleEl.value;
                    document.getElementById('content').value = JSON.stringify(data, null, 2);
                }
                // 初始化
                document.addEventListener('DOMContentLoaded', generateJSON);
            </script>

            <hr>
            <div class="mb-3">
                <label class="form-label">附件（最多 6 个，每个可填写备注）</label>
                {% set existing_count = attachments|length if attachments else 0 %}
                <div class="mb-2 text-muted">已上传：{{ existing_count }} / 6</div>

                <div id="upload-area" data-existing-count="{{ existing_count or 0 }}">
                    <div class="row gx-2 upload-row">
                        <div class="col-12 col-md-6 mb-2">
                            <div class="input-group">
                                <input class="form-control" type="file" name="attachments" accept=".pdf,.ppt,.pptx,.jpg,.jpeg,.png,.gif,.doc,.docx,.xls,.xlsx">
                                <input class="form-control" type="text" name="attachment_remarks" placeholder="备注（可选）">
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mt-2">
                    <button type="button" id="add-attachment" class="btn btn-sm btn-outline-primary">＋ 添加附件</button>
                    <span class="text-muted ms-2">最多 6 个</span>
                </div>
            </div>

            {% if attachments %}
                <div class="mb-3">
                    <label class="form-label">已上传附件（编辑时可选择删除）</label>
                    <ul>
                        {% for a in attachments %}
                            {% if a is mapping %}
                                <li>
                                    <input type="checkbox" name="delete_attachments" value="{{ a.saved_name }}"> 删除
                                    <a href="/uploads/{{ a.saved_name }}" target="_blank">{{ a.orig_name or a.saved_name }}</a>
                                    {% if a.remark %}<div class="text-muted small">备注：{{ a.remark }}</div>{% endif %}
                                </li>
                            {% else %}
                                <li>
                                    <input type="checkbox" name="delete_attachments" value="{{ a }}"> 删除
                                    <a href="/uploads/{{ a }}" target="_blank">{{ a }}</a>
                                </li>
                            {% endif %}
                        {% endfor %}
                    </ul>
                </div>
            {% endif %}

            <script>
                (function(){
                    const maxCount = 6;
                    const addBtn = document.getElementById('add-attachment');
                    const uploadArea = document.getElementById('upload-area');
                    const existingCount = parseInt(uploadArea.dataset.existingCount) || 0;

                    function countRows(){
                        return uploadArea.querySelectorAll('.upload-row').length + existingCount;
                    }

                    addBtn.addEventListener('click', function(){
                        if(countRows() >= maxCount) return alert('最多只能添加 6 个附件');
                        const row = document.createElement('div');
                        row.className = 'row gx-2 upload-row';
                        row.innerHTML = `\
                            <div class="col-12 col-md-6 mb-2">\
                                <div class="input-group">\
                                    <input class="form-control" type="file" name="attachments" accept=\".pdf,.ppt,.pptx,.jpg,.jpeg,.png,.gif,.doc,.docx,.xls,.xlsx\">\
                                    <input class="form-control" type="text" name="attachment_remarks" placeholder="备注（可选）">\
                                    <button type="button" class="btn btn-outline-danger btn-remove">删除</button>\
                                </div>\
                            </div>`;
                        uploadArea.appendChild(row);
                        row.querySelector('.btn-remove').addEventListener('click', function(){ row.remove(); });
                    });
                })();
            </script>

            <div class="d-flex justify-content-end gap-2">
                <a class="btn btn-secondary" href="{{ request.headers.get('Referer','/meetings') }}">取消</a>
                <button class="btn btn-primary" type="submit">{{ '更新记录' if editing else '保存记录' }}</button>
            </div>
        </form>
    </div>
</div>
{% endblock %}
